from models.entity.maintenance import Maintenance
from flask import Blueprint,request
import datetime
import json
from utils.result import result

"""
维保记录管理
"""
mod = Blueprint("core_maintenance", __name__, url_prefix="/core/maintenance", template_folder="templates", static_folder="static")


@mod.route("/add/",methods=["POST"])
def maintenance_add():
    """
    添加维保记录
    request: json
        {
                "time":"YYYY-MM-DD hh:mm",
                "maintenance_type":"维保类型",
                "project_name":"项目名称",
                "facility_id":2,
                "pump_house_location":"泵房地址",
                "device_id":"维修设备id",
                "user_id":"维修人员id",
                "reason":"故障原因"
        }
    """
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0,error_code=-1,error_msg="json format error")
    if "id" in data:
        data.pop("id")
    try:
        data["time"]=datetime.datetime.strptime(data["time"],"%Y-%m-%d %H:%M")
    except:
        return result(success=0,error_code=-1,error_msg="time格式错误")
    the_maintenance = Maintenance()
    try:
        the_maintenance.from_dict(data)
    except RuntimeError as e:
        return result(success=0,error_code=-2,error_msg=str(e))
    if the_maintenance.save() is False:
        return result(success=0,error_code=-2,error_msg="保存错误")
    else:
        return result(success=1)


@mod.route("/edit/",methods=["POST"])
def maintenance_edit():
    """
    编辑维保记录
    request: json
        {
                "id":1,
                "time":"YYYY-MM-DD hh:mm",
                "maintenance_type":"维保类型",
                "project_name":"项目名称",
                "facility_id":2,
                "pump_house_location":"泵房地址",
                "device_id":"维修设备id",
                "user_id":"维修人员id",
                "reason":"故障原因"
        }
    """
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    the_maintenance=Maintenance().get_entity_by_id(data["id"])
    if "device_name" in data:
        data.pop("device_name")
    if "device_code" in data:
        data.pop("device_code")
    if "lng" in data:
        data.pop("lng")
    if "lat" in data:
        data.pop("lat")
    if "username" in data:
        data.pop("username")
    if the_maintenance is None:
        return result(success=0,error_code=-1,error_msg="指定维保记录不存在")
    try:
        data["time"]=datetime.datetime.strptime(data["time"],"%Y-%m-%d %H:%M")
    except:
        return result(success=0,error_code=-1,error_msg="time格式错误")
    try:
        the_maintenance.from_dict(data)
    except RuntimeError as e:
        return result(success=0, error_code=-1, error_msg=str(e))
    if the_maintenance.save() is True:
        return result(success=1)
    else:
        return result(success=0,error_code=-2,error_msg="未知错误")


@mod.route("/del/",methods=["POST"])
def maintenance_del():
    """
    删除维保记录
    request: json
    {
        "id":1
    }
    """
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json format error")
    if "id" not in data:
        return result(success=0, error_code=-1, error_msg="数据不完整")
    the_maintenance=Maintenance().get_entity_by_id(data["id"])
    if the_maintenance is None:
        return result(success=0, error_code=-2, error_msg="指定维保记录不存在")
    if the_maintenance.delete():
        return result(success=1)
    else:
        return result(success=0, error_code=-2, error_msg="删除异常")


@mod.route("/get_all/",methods=["POST"])
def maintenance_get_all():
    """
    获取所有维保记录
    无请求参数
    """
    all_maintenance=Maintenance().get_list_all()
    tlist = [item.to_dict() for item in all_maintenance]
    return result(success=1,data=tlist)


@mod.route("/get_all_by_device_id/",methods=["POST"])
def maintenance_get_all_by_device_id():
    """
    根据设备id获取维保记录, 或根据时间间隔获取维保设备记录
    """
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json format error")
    if "id" not in data:
        return result(success=0, error_code=-1, error_msg="数据不完整")
    else:
        id_num=data["id"]
    if ("begin_time" not in data) or ("end_time" not in data):
        all_maintenances = Maintenance.get_maintenance_all_by_device_id(id_num)
        tlist = [item.to_dict() for item in all_maintenances]
        return result(success=1, data=tlist)
    else:
        try:
            begin_time=datetime.datetime.strptime(data["begin_time"], "%Y-%m-%d")
            end_time=datetime.datetime.strptime(data["end_time"], "%Y-%m-%d")
        except:
            return result(success=0, error_code=-1, error_msg="时间格式错误")
        all_maintenances=Maintenance.query.filter(Maintenance.time.between(begin_time, end_time)).filter(Maintenance.device_id == id_num).all()
        tlist=[item.to_dict() for item in all_maintenances]
        return result(success=1, data=tlist)


@mod.route("/get_all_by_time/",methods=["POST"])
def maintenance_get_all_by_time():
    """
    根据时间区间查询维保记录
    {
        "device_id": 1,
        "begin_time": "2017-01-01",
        "end_time": "2018-01-01"
    }
    """
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json format error")
    if "device_id" not in data:
        return result(success=0, error_code=-1, error_msg="数据不完整")
    else:
        try:
            begin_time=datetime.datetime.strptime(data["begin_time"],"%Y-%m-%d")
            end_time=datetime.datetime.strptime(data["end_time"],"%Y-%m-%d")
        except:
            return result(success=0, error_code=-1, error_msg="时间格式错误")
        all_maintenances = Maintenance.query.filter(Maintenance.time.between(begin_time, end_time)).filter(Maintenance.device_id == data["device_id"]).all()
        tlist = [item.to_dict() for item in all_maintenances]
        return result(success=1,data=tlist)
